package com.zidian.study.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zidian.study.activity.AboutActivity;
import com.zidian.study.activity.LoginActivity;
import com.zidian.study.activity.MyScoreActivity;
import com.zidian.study.activity.PersonOpitionActivity;
import com.zidian.study.activity.StudyChangeActivity;
import com.zidian.study.activity.StudySetPasswordActivity;
import com.zidian.study.activity.TreasureActivity;
import com.zidian.study.activity.UserStatisticsActivity;
import com.zidian.study.bean.UserMessageBean;
import com.zidian.study.event.LotteryNumberChangeEvent;
import com.zidian.study.event.StudentInfoChangeEvent;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.SharedPreferenceUtils;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import com.zidian.student.trucks.R;

/**
 * Created by tangyangkai on treasure_chest16/5/10.
 */
public class PersonFragment extends BaseFragment implements View.OnClickListener {


    @Bind(R.id.study_image)
    CircleImageView studyImage;
    @Bind(R.id.study_name)
    TextView studyName;
    @Bind(R.id.study_class)
    TextView studyClass;
    @Bind(R.id.my_score_level)
    TextView myScoreLevel;
    @Bind(R.id.my_score_experience)
    TextView myScoreExperience;
    @Bind(R.id.study_message)
    LinearLayout studyMessage;
    //    @Bind(R.id.study_evaluate)
//    TextView studyEvaluate;
    @Bind(R.id.study_read)
    TextView studyRead;
    @Bind(R.id.study_opition)
    LinearLayout studyOpinition;
    @Bind(R.id.study_change_psw)
    LinearLayout studyChangePsw;
    @Bind(R.id.study_out)
    LinearLayout studyOut;
    @Bind(R.id.my_score_progress)
    ProgressBar myScoreProgress;
    @Bind(R.id.study_about)
    LinearLayout studyAbout;

    private int lotteryNumber;
    UserMessageBean model = new UserMessageBean();
    PopupWindow popupWindow;


    @OnClick(R.id.study_about)
    void onAboutClick() {
        startActivity(AboutActivity.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tab_fragment_person;
    }


    public static PersonFragment newInstance() {
        return new PersonFragment();
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        try {
            run();
        } catch (IOException e) {
            e.printStackTrace();
        }
        studyMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (model.getData() != null) {
                    Intent intent = new Intent(getActivity(), StudyChangeActivity.class);
                    intent.putExtra("studyMessage", model);
                    startActivity(intent);
                }

            }
        });

        studyChangePsw.setOnClickListener(this);
        studyOpinition.setOnClickListener(this);
        studyOut.setOnClickListener(this);


    }

    /**
     * 我的积分
     */
    @OnClick(R.id.user_score)
    public void userScore() {
        if (model.getData() != null) {
            Intent intent = new Intent(getActivity(), MyScoreActivity.class);
            intent.putExtra("studyMessage", model);
            startActivity(intent);
        }

    }

    /**
     * 用户统计
     */
    @OnClick(R.id.user_statistics)
    public void userStatistics() {
        startActivity(UserStatisticsActivity.class);
    }

    /**
     * 我的宝箱
     */
    @OnClick(R.id.my_treasure)
    public void myTreasure() {
        if (model.getData() != null) {
            Intent intent = new Intent(getActivity(), TreasureActivity.class);
            intent.putExtra("lotteryNumber", lotteryNumber);
            startActivity(intent);
        } else {
            startActivity(TreasureActivity.class);
        }

    }

    /**
     * 接收学生信息改变事件，更新界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshStudentInfo(StudentInfoChangeEvent event) {
        if (event.isChanged()) {
            try {
                run();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接收抽奖次数改变事件
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshLotteryNunber(LotteryNumberChangeEvent event) {
        lotteryNumber = event.getLotteryNumber();
    }

    public void run() throws IOException {
        String loginUrl = Constant.URL_GOAL + "studentApp/selectMe";

        Map<String, String> map = new HashMap<>();
        map.put("studentId", GetUserInfo.getStudentId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(mActivity.getApplication(), "获取个人信息失败！");
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                model = gson.fromJson(response, UserMessageBean.class);
                if (model.isSuccess()) {
                    if (model != null) {
                        if (studyName == null) {
                            return;
                        }
                        if (model.getData().getMyNickName() == null) {
                            studyName.setText(getResources().getString(R.string.study_nick_name));
                            studyName.setTextColor(getResources().getColor(R.color.hint));
                        } else {
                            studyName.setText(model.getData().getMyNickName());
                        }
                        if (model.getData().getPersonalizedSignature() == null) {
                            studyClass.setText(getResources().getString(R.string.study_personalized_signature));
                            studyClass.setTextColor(getResources().getColor(R.color.hint));
                        } else {
                            studyClass.setText(model.getData().getStudentClass());
                        }
                        lotteryNumber = model.getData().getStudentLotteryNumber();
//                        studyEvaluate.setText(model.getData().getCommentNum() + "");
                        studyRead.setText(model.getData().getViewedNum() + "");
                        myScoreLevel.setText(model.getData().getStudentIntegralGrade() + "");
                        myScoreProgress.setProgress(model.getData().getStudentExperience());
                        myScoreExperience.setText(model.getData().getStudentExperience() + "/"
                                + model.getData().getStudentExperienceMax());
                        Glide.with(mActivity)
                                .load(model.getData().getStudentHeadPortrait())
                                .centerCrop()
                                .into(studyImage);

                    }
                }
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.study_change_psw:
                startActivity(StudySetPasswordActivity.class);
                break;
            case R.id.study_opition:
                startActivity(PersonOpitionActivity.class);
                break;
            case R.id.study_out:
                showPopupWindow();
                break;
        }
    }

    /**
     * 显示退出popupWindow
     */
    private void showPopupWindow() {
        if (popupWindow == null) {
            TextView drawerLayoutPopupWindowSureTV;
            TextView drawerLayoutPopupWindowCanCelTV;
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.mine_logout_popupwindow, null);
            drawerLayoutPopupWindowSureTV = (TextView) view.findViewById(R.id.drawerLayoutPopupWindowSureTV);
            drawerLayoutPopupWindowCanCelTV = (TextView) view.findViewById(R.id.drawerLayoutPopupWindowCanCelTV);
            drawerLayoutPopupWindowCanCelTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            drawerLayoutPopupWindowSureTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GetUserInfo.loginOut(mActivity);
                    SharedPreferenceUtils.clear();
                    startActivity(LoginActivity.class);
                    mActivity.finish();
                }
            });
            popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        }

        popupWindow.showAtLocation(studyOut, Gravity.CENTER, 0, 0);
    }
}

